package com.navinfo.collect.fragment

import android.app.Activity
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.navinfo.collect.R
import java.io.Serializable

class NIFragmentManager private constructor() : Serializable {
    //private constructor()构造器私有化
    private lateinit var mActivity: FragmentActivity;
    private lateinit var mFragmentManager: FragmentManager;
    private var mMenuFragmentId: Int = 0;
    private lateinit var mBottomSheetBehavior: BottomSheetBehavior<View>;
    private var currentFragment: BaseFragment? = null;
    fun init(
        activity: FragmentActivity,
        menuId: Int,
        bottomSheetBehavior: BottomSheetBehavior<View>
    ) {
        this.mActivity = activity
        this.mFragmentManager = activity.supportFragmentManager;
        this.mMenuFragmentId = menuId
        this.mBottomSheetBehavior = bottomSheetBehavior
    }

    private fun readResolve(): Any {//防止单例对象在反序列化时重新生成对象
        return instance
    }

    companion object {
        //通过@JvmStatic注解，使得在Java中调用instance直接是像调用静态函数一样，
        //NIFragmentManager.getInstance(),如果不加注解，在Java中必须这样调用: NIFragmentManager.Companion.getInstance().
        @JvmStatic
        //使用lazy属性代理，并指定LazyThreadSafetyMode为SYNCHRONIZED模式保证线程安全
        val instance: NIFragmentManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { NIFragmentManager() }
    }


    fun switchFragment(fragment: BaseFragment) {
        if (currentFragment == fragment) {
            return
        }
        mFragmentManager.fragments.forEach {
            if (it.isAdded && !it.isHidden) {
                mFragmentManager.beginTransaction().hide(it).commit()
            }
        }

        if (!fragment.isAdded) {
//            mFragmentManager.beginTransaction().add(R.id.main_fragment_layout,fragment).commit();
        } else {
            mFragmentManager.beginTransaction().show(fragment).commit();
        }
        currentFragment = fragment;
    }

    fun menuShowNewDataMenuFragment() {
        var fragment: NewDataFragment = NewDataFragment()
        mFragmentManager.beginTransaction().replace(R.id.activity_main_menu_fragment, fragment)
            .commit();
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HALF_EXPANDED)
    }
}